<?php

namespace backend\modules\bonus\forms;

use Yii;
use yii\base\Model;
use yii\web\NotFoundHttpException;
use common\models\common\Config;
use common\models\bonus\Bonus;
use common\models\bonus\BonusFl;
use common\models\member\Member;


class FlForm extends Model
{
    public $tp;
    public $username;
    public $bonus;

    private $_member;

    public function rules()
    {
        return [
            [['username', 'bonus', 'tp'], 'integer'],
            [['bonus'], 'number'],
            ['username', 'checkMember'],
        ];
    }

    public function checkMember()
    {
        $this->_member = Member::findOne(['username'=>$this->username]);
        if (!$this->_member) {
            $this->addError('username', '会员不存在');
        }
    }

    public function attributeLabels()
    {
        return [
            'username' => '得奖会员编号',
            'bonus' => '奖金额度',
            'tp' => '奖励类型',
        ];
    }

    public function calc()
    {
        if (!$this->validate()) {
            return false;
        }

        $res = Bonus::bonusFuLi($this->_member, $this->bonus);
        $model = new BonusFl();
        $model->member_id = $this->_member->id;
        $model->bonus = $res['bonus'];
        $model->tax = $res['tax'];
        $model->fee = $res['fee'];
        $model->payment = $res['payment'];
        $model->tp = $this->tp;
        $model->created_at = time();
        if (!$model->save()) {
            throw new \Exception('信息保存失败', 1);
        }
        return true;
    }
}